package de.gwtprime.client.activities;

import java.util.List;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.web.bindery.requestfactory.shared.Receiver;

import de.gwtprime.client.ClientFactory;
import de.gwtprime.client.event.UserLoginAttemptEvent;
import de.gwtprime.client.event.handler.UserLoginAttemptEventHandler;
import de.gwtprime.client.places.UserAccountPlace;
import de.gwtprime.client.util.AppUtils;
import de.gwtprime.client.util.ErrorWidget;
import de.gwtprime.client.views.UserAccountView;
import de.gwtprime.client.viewsStatic.LoadingIndictator;
import de.gwtprime.client.viewsStatic.NavigationViewImpl.Section;
import de.gwtprime.shared.requestFactory.QuestionProxy;

public class UserAccountActivity extends AbstractActivity implements UserAccountView.Presenter{

	private ClientFactory clientFactory;
	private String name;
	public UserAccountActivity(UserAccountPlace place, ClientFactory clientFactory) {
		this.clientFactory = clientFactory;
		this.name = place.getName();
	}
	
	
	@Override
	public void start(final AcceptsOneWidget panel, EventBus eventBus) {
		
		final UserAccountView userAccountView = clientFactory.getUserAccountView();
		clientFactory.getEventBus().addHandler(UserLoginAttemptEvent.TYPE, new UserLoginAttemptEventHandler() {
			
			@Override
			public void onUserLoggedIn(UserLoginAttemptEvent event) {
				
				if(event.getUser()!=null)
					startWithLoggedInUser(panel, userAccountView);
				else{
					panel.setWidget(new ErrorWidget("Log in first"));
				}
				
			}
		});
		
		clientFactory.getNavigationView().activateSection(Section.USER_ACCOUNT);
		
		if(clientFactory.getUser()==null){
			panel.setWidget(new LoadingIndictator());
		}else{
			
			startWithLoggedInUser(panel, userAccountView);
		}
		
		
		// Load questions for the user
		clientFactory.getRequestFactory().questionRequest().getQuestionsForUser(clientFactory.getUser().getEmail(),5).fire(
				new Receiver<List<QuestionProxy>>(){
					public void onSuccess(List<QuestionProxy> questions) {
						userAccountView.setQuestions(questions);
					};
				});
					
		
		
	}


	private void startWithLoggedInUser(AcceptsOneWidget panel,
			final UserAccountView userAccountView) {
		AppUtils.trackPageview("UserAccountPage");
		userAccountView.setPresenter(this);
		userAccountView.setName(name);
		userAccountView.setUser(clientFactory.getUser());
		panel.setWidget(userAccountView.asWidget());
		
		userAccountView.setUser(clientFactory.getUser());
	}


	@Override
	public void goTo(Place place) {
		clientFactory.getPlaceController().goTo(place);
		
	}

	@Override
	public ClientFactory getClientFactory() {
		return clientFactory;
	}

}
